<template>
  <div id="app" class="wrapper wrapper-content animated fadeInRight v-cloak" v-cloak>
    <div class="row">
      <div class="ibox float-e-margins">
        <div class="ibox-content col-md-12">
          <form id="inspectionPlanForm" method="post" class="form m-t" @submit.prevent="save()" accept-charset="UTF-8">
            <input type="hidden" name="id" v-model="item.id"/>
            <input type="hidden" name="token" v-model="item.token"/>
            <input type="hidden" name="newFlag" v-model="newFlag"/>
            <div class="clearfix "></div>
            <div class="col-md-6">

              <div class="form-group clearfix">
                <label class="col-md-8 control-label">行政区划：</label>
                <div class="col-md-12">
                  <!--<input id="bean-regionId" name="regionId" v-model="item.regionId" class="form-control" type="text"-->
                  <!--placeholder="请输入行政区划" aria-describedby="bean-regionId-error" maxlength="100"-->
                  <!--aria-invalid="true">-->

                  <!--<input id="bean-regionName" name="regionName" v-model="item.regionName" class="form-control"-->
                  <!--type="hidden" placeholder="请输入行政区划名称" aria-describedby="bean-regionName-error" maxlength="100"-->
                  <!--aria-invalid="true">-->
                  <select data-placeholder="请选择省" class="input-sm"
                      required="" aria-required="true" aria-describedby="bean-areaA-error"
                      aria-invalid="true">
                    <option value="51">四川省</option>
                  </select>
                  <select data-placeholder="请选择市" class="input-sm"
                      required="" aria-required="true" aria-describedby="bean-areaB-error"
                      aria-invalid="true">
                    <option value="5110">内江市</option>
                  </select>
                  <select data-placeholder="请选择区县" class="input-sm"
                      required="" aria-required="true" aria-describedby="bean-areaC-error"
                      aria-invalid="true">
                    <option value="511025">资中县</option>
                  </select>
                  <input type="hidden" name="regionId" value="51,5110,511025"/>
                  <input type="hidden" name="regionName" value="四川省内江市资中县"/>
                </div>
              </div>

              <div class="form-group clearfix">
                <label class="col-md-8 control-label">等级：</label>
                <div class="col-md-12">
                  <!--<input id="bean-level" name="level" v-model="item.level" class="form-control" type="text"-->
                  <!--placeholder="请输入等级" required="" aria-required="true" aria-describedby="bean-level-error"-->
                  <!--maxlength="10" aria-invalid="true">-->
                  <select data-placeholder="选择等级" id="bean-level" name="level"
                      class="form-control" aria-describedby="bean-level-error" maxlength="50"
                      aria-invalid="true" required>
                    <option value="">--请选择等级--</option>
                    <option value="省级" :selected="'省级' === item.level">省级</option>
                    <option value="市级" :selected="'市级' === item.level">市级</option>
                    <option value="县级" :selected="'县级' === item.level">县级</option>
                    <option value="乡镇级" :selected="'乡镇级' === item.level">乡镇级</option>
                    <option value="村级" :selected="'村级' === item.level">村级</option>
                  </select>
                  <span id="bean-level-error" class="help-block m-b-none" for="bean-level"></span>
                </div>
              </div>

              <!--<div class="form-group clearfix">-->
              <!--<label class="col-md-8 control-label">河道：</label>-->
              <!--<div class="col-md-12">-->
              <!--&lt;!&ndash;<input id="bean-riverCourseCode" name="riverCourseCode" v-model="item.riverCourseCode"&ndash;&gt;-->
              <!--&lt;!&ndash;class="form-control" type="text" placeholder="请输入河道" required="" aria-required="true"&ndash;&gt;-->
              <!--&lt;!&ndash;aria-describedby="bean-riverCourseCode-error" maxlength="50" aria-invalid="true">&ndash;&gt;-->
              <!--<riverSelect :selected-code="item.riverCourseCode"/>-->
              <!--<span id="bean-riverCourseCode-error" class="help-block m-b-none" for="bean-riverCourseCode"></span>-->
              <!--</div>-->
              <!--</div>-->

              <div class="form-group clearfix">
                <label class="col-md-8 control-label">巡查周期：</label>
                <div class="col-md-12">
                  <!--取消河道选择，数据库此字段不能为空，用99999占位-->
                  <input type="hidden" name="riverCourseCode" value="99999"/>
                  <!--<input id="bean-cycle" name="cycle" v-model="item.cycle" class="form-control" type="text"-->
                  <!--placeholder="请输入巡查周期" aria-describedby="bean-cycle-error" maxlength="10" aria-invalid="true">-->
                  <select data-placeholder="选择巡查周期" id="bean-cycle" name="cycle" @click="cycleChange()" v-model="item.cycle"
                      class="form-control" aria-describedby="bean-cycle-error" maxlength="50"
                      aria-invalid="true">
                    <option value="">--请选择周期--</option>
                    <option value="年" :selected="'年' === item.cycle">年</option>
                    <option value="月" :selected="'月' === item.cycle">月</option>
                    <option value="周" :selected="'周' === item.cycle">周</option>
                  </select>
                  <span id="bean-cycle-error" class="help-block m-b-none" for="bean-cycle"></span>
                </div>
              </div>

            </div>
            <div class="col-md-6">

              <div class="form-group clearfix">
                <label class="col-md-8 control-label">应巡查次数：</label>
                <div class="col-md-12">
                  <input id="bean-times" name="times" v-model="item.times" class="form-control" type="text"
                      placeholder="请输入应巡查次数" aria-describedby="bean-times-error" maxlength="50" aria-invalid="true" required>
                  <span id="bean-times-error" class="help-block m-b-none" for="bean-times"></span>
                </div>
              </div>

              <div class="form-group clearfix">
                <label class="col-md-8 control-label">巡查人员类别：</label>
                <div class="col-md-12">
                  <!--<input id="bean-personType" name="personType" v-model="item.personType" class="form-control"-->
                  <!--type="text" placeholder="请输入巡查人员类别" aria-describedby="bean-personType-error" maxlength="10"-->
                  <!--aria-invalid="true">-->
                  <select data-placeholder="选择人员类别" id="bean-personType" name="personType"
                      class="form-control" aria-describedby="bean-personType-error" maxlength="50"
                      aria-invalid="true" required>
                    <option value="">--请选择人员类别--</option>
                    <option value="河长" :selected="'河长' === item.personType">河长</option>
                    <option value="巡查员" :selected="'巡查员' === item.personType">巡查员</option>
                  </select>
                  <span id="bean-personType-error" class="help-block m-b-none" for="bean-personType"></span>
                </div>
              </div>

              <div class="form-group clearfix">
                <label class="col-md-8 control-label">备注：</label>
                <div class="col-md-12">
                  <input id="bean-memo" name="memo" v-model="item.memo" class="form-control" type="text"
                      placeholder="请输入备注" aria-describedby="bean-memo-error" maxlength="255" aria-invalid="true">
                  <span id="bean-memo-error" class="help-block m-b-none" for="bean-memo"></span>
                </div>
              </div>

            </div>

            <div class="clearfix "></div>
            <div class="col-md-12">

              <div class="form-group clearfix">
                <label class="col-md-8 control-label">任务时间：</label>
                <div class="col-md-12" style="max-height: 400px">
                  <textarea class="hidden" aria-describedby="bean-taskTime-error" aria-invalid="true"
                      id="bean-taskTime" name="taskTime"
                      placeholder="请根据周期和巡查次数输入任务时间（须使用英文输入法）"
                      title="格式：开始时间,结束时间;开始时间,结束时间...
                            例如：
                        每年2次（输入月日和时间）：1-1 9:00:00,1-1 18:00:00;7-1 9:00:00,7-1 18:00:00
                        每月2次（输入日期和时间）：1 9:00:00,1 18:00:00;15 9:00:00,15 18:00:00
                        每周2次（输入星期和时间）：1 9:00:00,1 18:00:00;5 9:00:00,5 18:00:00"
                      style="height: 200px;width: 100%;" v-model="item.taskTime"></textarea>
                  <table class="table table-sm table-striped table-bordered table-hover center">
                    <thead id="header">
                    <template v-if="item.cycle === '年'">
                      <tr class="mytr">
                        <td width="40%">开始月份</td>
                        <td width="40%">开始日期</td>
                        <td width="40%">开始时间</td>
                        <td width="40%">结束月份</td>
                        <td width="40%">结束日期</td>
                        <td width="40%">结束时间</td>
                        <td width="20%">操作</td>
                      </tr>
                    </template>
                    <template v-else-if="item.cycle === '月'">
                      <tr class="mytr">
                        <td width="40%">开始日期</td>
                        <td width="40%">开始时间</td>
                        <td width="40%">结束日期</td>
                        <td width="40%">结束时间</td>
                        <td width="20%">操作</td>
                      </tr>
                    </template>
                    <template v-else-if="item.cycle === '周'">
                      <tr class="mytr">
                        <td width="20%">开始星期</td>
                        <td width="20%">开始时间</td>
                        <td width="20%">结束星期</td>
                        <td width="20%">结束时间</td>
                        <td width="20%">操作</td>
                      </tr>
                    </template>
                    <template v-else>
                      <tr>
                        <td>请选择巡查周期</td>
                      </tr>
                    </template>
                    </thead>
                    <tbody id="tbody" style="display:block; max-height: 200px;overflow-y: scroll">
                    <template v-if="item.cycle === '年' && timeTable.length > 0">
                      <!--<tr class="mytr" v-for="(tr,i) in timeTable" :id="'yearId'+tr.yearId">-->
                      <tr class="mytr" v-for="(tr,i) in timeTable" :id="tr">
                        <td width="40%"><input class="a" style="width: 50%" type="number" min="1" max="12" @keyup="validMax12" placeholder="输入/点击选择" required="required"></td>
                        <td width="40%"><input class="b" style="width: 50%" type="number" min="1" max="31" @keyup="validMax31" placeholder="输入/点击选择" required="required"></td>
                        <td width="40%"><input class="c" type="time" required="required"></td>
                        <td width="40%"><input class="a1" style="width: 50%" type="number" min="1" max="12" @keyup="validMax12" placeholder="输入/点击选择" required="required"></td>
                        <td width="40%"><input class="b1" style="width: 50%" type="number" min="1" max="31" @keyup="validMax31" placeholder="输入/点击选择" required="required"></td>
                        <td width="40%"><input class="d" type="time" required="required"></td>
                        <!--<td width="20%"><a href="javascript:void(0);" v-on:click="deleteBtn('yearId'+tr.yearId)">删除</a></td>-->
                        <td width="20%"><a href="javascript:void(0);" v-on:click="deleteBtn(tr)">删除</a></td>
                      </tr>
                    </template>
                    <template v-else-if="item.cycle === '月' && timeTable.length > 0">
                      <!--<tr class="mytr" v-for="(tr,i) in timeTable" :id="'monthId'+tr.monthId">-->
                      <tr class="mytr" v-for="(tr,i) in timeTable" :id="tr">
                        <td width="40%"><input class="a" style="width: 50%" type="number" min="1" max="31" @keyup="validMax31" placeholder="输入/点击选择" required="required"></td>
                        <td width="40%"><input class="b" type="time" required="required"></td>
                        <td width="40%"><input class="a1" style="width: 50%" type="number" min="1" max="31" @keyup="validMax31" placeholder="输入/点击选择" required="required"></td>
                        <td width="40%"><input class="c" type="time" required="required"></td>
                        <!--<td width="20%"><a href="javascript:void(0);" @click="deleteBtn('monthId'+timeTable.monthId)">删除</a></td>-->
                        <td width="20%"><a href="javascript:void(0);" v-on:click="deleteBtn(tr)">删除</a></td>
                      </tr>
                    </template>
                    <template v-else-if="item.cycle === '周' && timeTable.length > 0">
                      <!--<tr class="mytr" v-for="(tr,i) in timeTable" :id="'weekId'+tr.weekId">-->
                      <tr class="mytr" v-for="(tr,i) in timeTable" :id="tr">
                        <td width="20%"><input class="a" style="width: 50%" type="number" min="1" max="7" @keyup="validMax7" placeholder="输入/点击选择" required="required"></td>
                        <td width="20%"><input class="b" type="time" required="required"></td>
                        <td width="20%"><input class="a1" style="width: 50%" type="number" min="1" max="7" @keyup="validMax7" placeholder="输入/点击选择" required="required"></td>
                        <td width="20%"><input class="c" type="time" required="required"></td>
                        <!--<td width="20%"><a href="javascript:void(0);" @click="deleteBtn('weekId'+timeTable.weekId)">删除</a></td>-->
                        <td width="20%"><a href="javascript:void(0);" v-on:click="deleteBtn(tr)">删除</a></td>
                      </tr>
                    </template>
                    <template v-else-if="item.cycle === ''">

                    </template>
                    </tbody>
                    <tfoot id="addRow" class="center" style="cursor: pointer" @click="addRow()">
                    <tr>
                      <td colspan="5">点击添加任务时间</td>
                    </tr>
                    </tfoot>
                  </table>
                  <span id="bean-taskTime-error" class="help-block m-b-none" for="bean-taskTime"></span>
                </div>
              </div>
            </div>

            <div class="clearfix "></div>
            <div class="col-12 text-center" style="height: 50px;">
              <div>
                <input class="btn btn-primary" type="submit" value="保存"/> | <a @click="lbox.closeMyBoxLayer()" class="btn btn-danger" href="javascript:">返回</a>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>
<script type="text/javascript">
import '@/assets/css/style.css'

import $ from '@/assets/js/jquery-vendor.js'
import 'jquery.cookie'
import axios from 'axios'
import '@/assets/js/validate/validation-vendor.js'
import riverSelect from '../river/riverSelect'
import regionSelect from '../river/regionSelect'

// import VueUeditorWrap from 'vue-ueditor-wrap'
import {apiUtil, axiosContentType, site} from '@/assets/js/boss'

export default {
  data() {
    return {
      item: {},
      newFlag: 0,
      uuidToken: '',
      timeTable: []
    }
  },
  components: {
    riverSelect,
    regionSelect
  },
  mounted() {
    let that = window.$vueApp = this;
    document.getElementsByTagName('body')[0].className = 'fixed-sidebar full-height-layout';
    $('#inspectionPlanForm').validate();
    that.staff.init(function () {
      that.newFlag = sessionStorage.getItem(site.inspectionPlan.info);
      if (that.newFlag) that.uuidToken = apiUtil.guid();
      if (apiUtil.existSessionKey(site.inspectionPlan.info)) {
        that.info();
      }
    });
  },
  updated() {
    let that = window.$vueApp = this;
    if (!that.item.cycle) {
      $('#bean-cycle').find("option:contains('')").attr('selected', true);
    }
    that.cycleChange();
  },
  methods: {
    info() {
      let that = window.$vueApp = this;
      axios.get(site.inspectionPlan.info + sessionStorage.getItem(site.inspectionPlan.info), {}).then(function (response) {
        const result = response.data;
        if (result.code === 0) {
          that.item = result.data;
          // TODO 填充任务时间 03-01 09:00:00,3-1 18:00:00;11-15 9:00:00,11-15 18:00:00
          let taskTime = result.data.taskTime
          let num = taskTime.split(';').length;
          console.log(num)
          for (let i = 0; i < num; i++) {
            console.log(i)
            that.timeTable[i] = new Date().getTime().toString() + i;
            console.log(that.timeTable[i])
          }
          console.log(taskTime)
          console.log(that.timeTable)
          setTimeout(function () {
            let times = taskTime.split(';');
            for (let n = 0; n < num; n++) {
              let start = times[n].split(',')[0]
              let end = times[n].split(',')[1]
              if (result.data.cycle === '年') {
                let startMonth = start.split('-')[0]
                let startDay = start.split(' ')[0].split('-')[1]
                let startTime = start.split(' ')[1]
                let endMonth = end.split('-')[0]
                let endDay = end.split(' ')[0].split('-')[1]
                let endTime = end.split(' ')[1]
                $('#' + that.timeTable[n]).find('.a').val(startMonth)
                $('#' + that.timeTable[n]).find('.b').val(startDay)
                $('#' + that.timeTable[n]).find('.c').val(startTime)
                $('#' + that.timeTable[n]).find('.a1').val(endMonth)
                $('#' + that.timeTable[n]).find('.b1').val(endDay)
                $('#' + that.timeTable[n]).find('.d').val(endTime)
              } else {
                let startDay = start.split(' ')[0]
                let startTime = start.split(' ')[1]
                let endDay = end.split(' ')[0]
                let endTime = end.split(' ')[1]
                $('#' + that.timeTable[n]).find('.a').val(startDay)
                $('#' + that.timeTable[n]).find('.b').val(startTime)
                $('#' + that.timeTable[n]).find('.a1').val(endDay)
                $('#' + that.timeTable[n]).find('.c').val(endTime)
              }
            }
          }, 500)
        } else {
          alert(result.message);
        }
      });
    },
    save() {
      let that = window.$vueApp = this;
      // 组装任务时间
      that.item.taskTime = '';
      for (let i in that.timeTable) {
        if (that.item.cycle === '年') {
          let startMonth = $('#' + that.timeTable[i]).find('.a').val();
          let startDay = $('#' + that.timeTable[i]).find('.b').val();
          let startTime = $('#' + that.timeTable[i]).find('.c').val().split(':').length === 2 ? $('#' + that.timeTable[i]).find('.c').val() + ':00' : $('#' + that.timeTable[i]).find('.c').val()
          let engMonth = $('#' + that.timeTable[i]).find('.a1').val();
          let endDay = $('#' + that.timeTable[i]).find('.b1').val();
          let endTime = $('#' + that.timeTable[i]).find('.d').val().split(':').length === 2 ? $('#' + that.timeTable[i]).find('.d').val() + ':00' : $('#' + that.timeTable[i]).find('.d').val()
          let time = startMonth + '-' + startDay + ' ' + startTime + ',' + engMonth + '-' + endDay + ' ' + endTime + ';';
          // alert(time)
          that.item.taskTime += time
        } else if (that.item.cycle === '月') {
          let startDay = $('#' + that.timeTable[i]).find('.a').val();
          let startTime = $('#' + that.timeTable[i]).find('.b').val().split(':').length === 2 ? $('#' + that.timeTable[i]).find('.b').val() + ':00' : $('#' + that.timeTable[i]).find('.b').val()
          let endDay = $('#' + that.timeTable[i]).find('.a1').val();
          let endTime = $('#' + that.timeTable[i]).find('.c').val().split(':').length === 2 ? $('#' + that.timeTable[i]).find('.c').val() + ':00' : $('#' + that.timeTable[i]).find('.c').val()
          let time = startDay + ' ' + startTime + ',' + endDay + ' ' + endTime + ';';
          // alert(time)
          that.item.taskTime += time
        } else if (that.item.cycle === '周') {
          let startWeek = $('#' + that.timeTable[i]).find('.a').val();
          let startTime = $('#' + that.timeTable[i]).find('.b').val().split(':').length === 2 ? $('#' + that.timeTable[i]).find('.b').val() + ':00' : $('#' + that.timeTable[i]).find('.b').val()
          let endWeek = $('#' + that.timeTable[i]).find('.a1').val();
          let endTime = $('#' + that.timeTable[i]).find('.c').val().split(':').length === 2 ? $('#' + that.timeTable[i]).find('.c').val() + ':00' : $('#' + that.timeTable[i]).find('.c').val()
          let time = startWeek + ' ' + startTime + ',' + endWeek + ' ' + endTime + ';';
          // alert(time)
          that.item.taskTime += time
        }
      }
      that.item.taskTime = that.item.taskTime.substring(0, that.item.taskTime.length - 1)
      // alert(that.item.taskTime)
      $('#bean-taskTime').val(that.item.taskTime);
      if ($('#inspectionPlanForm').valid() && that.validTaskTime()) {
        axios.post(site.inspectionPlan.save, $('#inspectionPlanForm').serialize(),
            axiosContentType.xWwwFormUrlencoded).then(function (response) {
          const result = response.data;
          // console.info("获取数据.." + JSON.stringify(result));
          if (result.code === 0) {
            parent.$vueApp.page();
            alert('保存成功!');
            that.lbox.closeMyBoxLayer()
          } else {
            alert(result.message);
          }
        });
      }
    },
    validTaskTime() {
      // 周期
      let cycle = $('#bean-cycle').val();
      // 次数
      let times = Number.parseInt($('#bean-times').val());
      // 时间
      let taskTime = $('#bean-taskTime').val();
      if (taskTime !== ' ' && taskTime) {
        taskTime = taskTime.split(';');
        if (times !== taskTime.length) {
          alert('任务时间和任务次数不相等');
          return false;
        }
        let fmt = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
        // fmt = /^([1-2][0-9][0-9][0-9]-[0-1]{0,1}[0-9]-[0-3]{0,1}[0-9])\s(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d$/
        if (cycle === '年') {
          for (let i = 0; i < times; i++) {
            let start = '2020-' + taskTime[i].split(',')[0];
            let end = '2020-' + taskTime[i].split(',')[1];
            if (!start.match(fmt) || !end.match(fmt)) {
              alert('任务时间格式不正确' + start + ' ' + end);
              return false;
            }
          }
        } else { // 月和周都可用下面方法验证
          for (let i = 0; i < times; i++) {
            let start = '2020-1-' + taskTime[i].split(',')[0];
            let end = '2020-1-' + taskTime[i].split(',')[1];
            if (!start.match(fmt) || !end.match(fmt)) {
              alert('任务时间格式不正确' + start + ' ' + end);
              return false;
            }
          }
        }
      }
      return true;
    },
    addRow() {
      let that = window.$vueApp = this;
      console.log(that.item.cycle)
      if (!that.item.cycle) {
        alert('请选择任务周期')
      } else {
        let id = new Date().getTime().toString();
        that.timeTable.push(id);
        console.log(that.timeTable)
        // if (that.item.cycle === '年') {
        //   that.timeTable.push({yearId: new Date().getTime()});
        // } else if (that.item.cycle === '月') {
        //   that.timeTable.push({monthId: new Date().getTime()});
        // } else if (that.item.cycle === '周') {
        //   that.timeTable.push({weekId: new Date().getTime()});
        // }
      }
    },
    cycleChange() {
      // let that = window.$vueApp = this;
      // that.timeTable.length = 0;
    },
    deleteBtn(id) {
      // alert(id)
      // let index = that.timeTable.tabs.indexOf(id);
      // if (index !== -1) { //当没有多余tab时就不再删除
      //   this.formData.tabs.splice(index, 1)
      // }
      let that = window.$vueApp = this;
      let index = that.timeTable.indexOf(id)
      // alert(index)
      if (index !== -1) {
        that.timeTable.splice(index, 1)
      }
    },
    validMax12(evt) {
      let event = evt;
      let val = event.currentTarget.value;
      if (val > 12) {
        event.currentTarget.value = 12;
      }
      if (val < 1) {
        event.currentTarget.value = 1;
      }
    },
    validMax31(evt) {
      let event = evt;
      let val = event.currentTarget.value;
      if (val > 31) {
        event.currentTarget.value = 31;
      }
      if (val < 1) {
        event.currentTarget.value = 1;
      }
    },
    validMax7(evt) {
      let event = evt;
      let val = event.currentTarget.value;
      if (val > 7) {
        event.currentTarget.value = 7;
      }
      if (val < 1) {
        event.currentTarget.value = 1;
      }
    }
  }
}
</script>
<style>
.mytr {
  display: table;
  width: 100%;
  table-layout: fixed;
  text-align: left;
}

#addRow:hover {
  background-color: #E4E6E9;
}
</style>
